package com.cuihaodong.controller;
/**
 * @author cuihaodong
 */

import com.cuihaodong.pojo.InstanceInfo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Component
public class EurekaClientProvider implements InitializingBean {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${eurekaServer.ip}")
    private String serverIp;

    @Value("${eurekaServer.port}")
    private String serverPort;

    @Value("${eurekaClient.ip}")
    private String providerIp;

    @Value("${eurekaClient.port}")
    private String providerPort;

    @Value("${eurekaClient.applicationName}")
    private String applicationName;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(restTemplate);
        //启动服务客户端时,注册服务
        System.out.println(serverPort);
        InstanceInfo instanceInfo = new InstanceInfo();
        instanceInfo.setIp("192.288.1.1");
        instanceInfo.setPort(providerPort);
        instanceInfo.setApplicationName(applicationName);
        instanceInfo.setRegisterDate(new Date());
        System.out.println(instanceInfo);
        String url = "http://"+serverIp+":"+serverPort+"/eurekaServer/registerService";
        String msg = restTemplate.postForObject(url, instanceInfo, String.class);
        System.out.println(msg);
    }

    /**
     * 每隔30s发送一次心跳
     */
    @Scheduled(cron = "*/30 * * * * ?")
    public void sendBeat(){
        String url = "http://"+serverIp+":"+serverPort+"/eurekaServer/updateService";

        InstanceInfo instanceInfo = new InstanceInfo();

        instanceInfo.setIp(providerIp);
        instanceInfo.setPort(providerPort);
        instanceInfo.setApplicationName(applicationName);
        instanceInfo.setRegisterDate(new Date());

        String s = restTemplate.postForObject(url,instanceInfo, String.class);
        System.out.println(s);
    }
}
